<?php

namespace app\admin\controller\project;

use app\admin\model\ProjectCate;

use app\admin\model\SystemVillage;
use app\admin\model\User;
use app\admin\service\annotation\MiddlewareAnnotation;
use app\common\controller\AdminController;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\common\enum\ProjectEnum;
use app\common\enum\StatusEnum;
use app\Request;
use think\App;
use think\response\Json;

#[ControllerAnnotation(title: '项目管理')]
class Projects extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = new \app\admin\model\Projects();
        $this->assign('cate', ProjectCate::column('title', 'id'));
        $this->assign('user', User::column('nickname', 'id'));
        $this->assign('village', SystemVillage::column('name', 'id'));
        $this->assign('projectStatus', ProjectEnum::getStatusDesc());
        $this->assign('approveStatus', StatusEnum::getStatusDesc());
    }

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            if (input('selectFields')) return $this->selectList();
            list($page, $limit, $where) = $this->buildTableParams();
            // 单独处理用户相关查询条件
            $userIdConditions = [];
            foreach ($where as $key => $condition) {
                if (isset($condition[0])) {
                    if ($condition[0] === 'user.nickname') {
                        if (!empty($condition[2])) {
                            $users = User::where('nickname', $condition[1], $condition[2])
                                ->field('id')
                                ->select()
                                ->toArray();

                            if (!empty($users)) {
                                $userIds = array_column($users, 'id');
                                $userIdConditions[] = ['user_id', 'IN', $userIds];
                            } else {
                                // 没有找到匹配用户时，添加不可能满足的条件
                                $userIdConditions[] = ['user_id', '=', -1];
                            }
                        }
                        // 移除原始的 user.nickname 条件
                        unset($where[$key]);
                    }
                }
            }

            // 合并用户ID条件到主查询条件中
            $where = array_merge($where, $userIdConditions);

            $count = self::$model::where($where)->count();
            $list = self::$model::with(['user', 'cate'])->where($where)->page($page, $limit)->order($this->sort)->select()->toArray();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
}